import TabPageItem from './tab_page_item.js'
import localforage from 'localforage'
import { ElMessage } from 'element-plus';
// import { getPageInfo, getPageCpns } from './query'
class TabPages {
	_pages = {} // pageid ---> Lxy_page_define
	static _instance = null
	static instance() {
		if (this._instance === null) {
			this._instance = new TabPages()
		}

		return this._instance
	}

	getPageKey(pageID) {
		return 'lxy_tab_page_' + pageID
	}
	// 返回 Lxy_page_define 对象
	async getPage(id) {
		// this.removeAll()
		const pageid = this.getPageKey(id)
		// if (this._pages.hasOwnProperty(pageid)) {
		// 	console.log('this._pages[pageid]', this._pages[pageid])
		// 	return this._pages[pageid]
		// }
		console.log('[Debug][TabPages]Load page from local forage, id:', id)
		const page = await localforage.getItem(pageid)
		if (page !== null) {
			console.log('[Debug][TabPages]Page defines from local forage: ', page)
			const page2 = new TabPageItem()
			page2._pageDefines = page
			this._pages[pageid] = page2
			return page2
		}

		const pageItem = new TabPageItem()
		const page_define = await pageItem.loadPage(id)
		console.log('page_define', page_define)
		if (page_define === null) {
			console.error('[Error][TabPages]The page is not exist, pageid: ', id)
			ElMessage({
				message: '页面不存在或配置错误',
				type: 'error',
				duration: BASE_API.MSG_SHOW_TIME,
			});
			return null
		}

		console.log('[Debug][TabPages]Load page from server:', id, page_define)
		this._pages[pageid] = pageItem
		console.log('this._pages[pageid]this._pages[pageid]this._pages[pageid]', this._pages[pageid], pageItem)
		await localforage.setItem(pageid, page_define)
		return pageItem
	}

	check() {
		// 查询页面是否有更新,如果有更新，则调用 removeAll 删除所有缓存
		this.removeAll()
	}

	removeAll() {
		// this._pages.splice(0, this._pages.length)
		this._pages = {}
		localforage.clear()
	}
	removePage(id) {
		const pageid = this.getPageKey(id)
		if (this._pages.hasOwnProperty(pageid)) {
			this._pages[pageid] = null
		}
		localforage.removeItem(pageid)
	}
}

export default TabPages
